import { useContext, useEffect, useState } from 'react';
import { Row, Col, Button, message, Spin } from 'antd';
import { useRequest, useMount } from 'ahooks';
import { pickBy } from 'lodash';
import { history } from 'umi';
import ProForm from '@ant-design/pro-form';
import ActionPersonItem from '../ActionPersonItem/index';
import { required, validImageWhenSubmit } from '@/utils/form/rules';
import { WhetherService, PersonnelEntryState } from '../../interface';
import { ProColumnType } from '@ant-design/pro-table';
import styles from './index.scss';
import { ActionMode } from '../AddPerson/interface';
import {
    batchEditUser,
    editUser,
    fetchUserDetail,
} from '@/service/personnelEntry';
import {
    transformToSubmitData,
    transformToFormData,
    findCascaderValue,
} from '../AddPerson/index';
import { toPersonnelEntry } from '../..';
import useAutoInjectCateInfo from '../../hooks/useAutoInjectCateInfo';
import { PageTabActionContext } from '@/layouts';

export const modify_params_keys = [
    'no',
    'no_type',
    'username',
    'avatar',
    'army_id',
    'corps_id',
    'serve_status',
    'sex',
    'age',
    'address',
];

export const personColumnsList: ProColumnType<PersonnelEntryState>[] = [
    {
        title: '用户名',
        valueType: 'text',
        key: 'username',
        formItemProps: {
            rules: [required('请输入用户名')],
        },
    },
    { title: '年龄', valueType: 'text', key: 'age' },
    {
        title: '性别',
        valueType: 'select',
        key: 'sex',
        valueEnum: {
            0: '未知',
            1: '女',
            2: '男',
        },
    },
    {
        title: '是否服役',
        key: 'serve_status',
        valueType: 'select',
        formItemProps: {
            rules: [required('请输入服役状态')],
        },
        valueEnum: {
            [WhetherService.是]: {
                text: WhetherService[WhetherService.是],
            },
            [WhetherService.否]: {
                text: WhetherService[WhetherService.否],
            },
        },
    },
    {
        title: '所属军队',
        key: 'army_id',
        valueType: 'cascader',
        fieldProps: {
            options: [],
        },
        formItemProps: {
            rules: [required('请输入所属军队')],
        },
    },
    {
        title: '兵种',
        key: 'corps_id',
        valueType: 'select',
        formItemProps: {
            rules: [required('请输入兵种')],
        },
        valueEnum: {},
    },
    {
        title: '证件类型',
        key: 'no_type',
        valueType: 'select',
        formItemProps: {
            rules: [required('请输入证件类型')],
        },
        valueEnum: {},
    },
    {
        title: '证件编号',
        key: 'no',
        formItemProps: {
            rules: [required('请输入证件编码')],
        },
    },
    {
        title: '地址',
        key: 'address',
    },
];

export default function ModifyPerson(props: any) {
    const { removeCurrentTab } = useContext(PageTabActionContext);
    const [form] = ProForm.useForm();
    const [keyList, setKeyList] = useState<number[]>([]);
    const query = props.location.query;

    const mode = query.mode ?? ActionMode.One;
    const user_id = query.id;

    const {
        loading: loadingByDetailInfo,
        data,
        run: loadUserDetailInfo,
    } = useRequest(async (id: string) => {
        const res = await fetchUserDetail(id);
        if (res.code !== 200) {
            message.error(res.msg || '服务器发生错误');
            return;
        }

        const data = {
            ...form.getFieldsValue(true),
            [res.data.id]: transformToFormData([res.data]).reduce(
                (result: any, item: any, index: number) => {
                    result[index] = item;
                    return result;
                },
                {},
            )[0],
        };

        form.setFieldsValue(data);

        return data[res.data.id];
    });

    /** 提交修改 */
    const { loading, run: batchModifyUserHandler } = useRequest(
        async (rawValues: any) => {
            const values = transformToSubmitData(Object.values(rawValues)).map(
                (item: any) => {
                    return {
                        ...pickBy(item, (val, key) =>
                            modify_params_keys.includes(key),
                        ),
                        user_id: item.id,
                    };
                },
            );

            let res;
            if (mode === ActionMode.One) {
                res = await editUser(values[0]);
            } else {
                res = await batchEditUser(JSON.stringify(values));
            }

            if (res.code !== 200) {
                message.error(res.msg);
                return;
            }

            message.success('修改成功');
            // history.push('/personnelEntry');
            removeCurrentTab();
        },
    );

    /** 自动注入枚举类型 */
    const {
        columns,
        data: cateInfo,
        loading: loadingByCateInfo,
    } = useAutoInjectCateInfo(personColumnsList);

    useMount(() => {
        if (mode === ActionMode.One) {
            loadUserDetailInfo(user_id);
            setKeyList([user_id]);
        } else {
            const users = Array.isArray(user_id) ? user_id : [user_id];
            setKeyList(users.map((item: string) => Number(item)));
            users.map((item: string) => loadUserDetailInfo(item));
        }
        console.log(user_id);
    });

    useEffect(() => {
        if (!cateInfo || !data) return;
        const army_id = data.army_id ?? [];

        if (!army_id.length) return;

        const result = findCascaderValue(cateInfo, army_id[0]);
        form.setFieldsValue({
            [data.id]: {
                ...data,
                army_id: result,
            },
        });
    }, [cateInfo, data]);

    /** 如果id异常，不显示 */
    if (!user_id) return null;
    return (
        <div>
            <Spin
                spinning={loading || loadingByDetailInfo || loadingByCateInfo}
            >
                <ProForm
                    form={form}
                    submitter={false}
                    onFinish={async () => {
                        batchModifyUserHandler(form.getFieldsValue(true));
                    }}
                    style={{ marginBottom: '50px' }}
                >
                    <Row gutter={[0, 16]}>
                        {keyList.map((item) => (
                            <Col span={24} className={styles.personItem}>
                                <ActionPersonItem
                                    form={form}
                                    prefix={item}
                                    onReset={() => {
                                        form.resetFields([item]);
                                    }}
                                    columns={columns}
                                    uploadProps={{
                                        rules: [
                                            validImageWhenSubmit('请上传头像'),
                                        ],
                                    }}
                                />
                            </Col>
                        ))}
                    </Row>
                </ProForm>
            </Spin>
            <Row justify="end" className={styles.controller}>
                <Col>
                    <Button
                        onClick={() => {
                            removeCurrentTab();
                            toPersonnelEntry();
                        }}
                    >
                        取消
                    </Button>
                    <Button
                        style={{ marginLeft: 10 }}
                        onClick={() => form.submit()}
                    >
                        提交
                    </Button>
                </Col>
            </Row>
        </div>
    );
}
